package com.brkj.test;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.brkj.httpInterface.BaseAjaxParams;
import com.brkj.httpInterface.HttpInterface;
import com.brkj.httpInterface.HttpInterface.HIF_GetExamDetail;
import com.brkj.httpInterface.NomalResult;
import com.brkj.main.R;
import com.brkj.test.model.DS_Exam;
import com.brkj.test.model.DS_Exam_detail_ques;
import com.brkj.test.model.DS_QuesRecord;
import com.brkj.util.ConstAnts;
import com.brkj.util.MyAjaxCallBack;
import com.brkj.util.TimeHelp;
import com.brkj.util.Util;
import com.brkj.util.view.*;
import com.dgl.sdk.util.DBStore;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class RealExamDetailActivity extends BaseActionBarActivity{

    private final static long EXAM_TIME = 3600000;
    private long untilFinishedTime;

	private MyViewPager viewPager;
	private ArrayList<View> views = new ArrayList<View>();
	private ArrayList<QuestionItem> questionViewList = new ArrayList<QuestionItem>();
	private String examPaperID;
	
	private List<DS_Exam_detail_ques> quesList;

	private TextView doProgress;
	private TextView wrongNum;

    private TextView haveTime;

	private int quesHavedoNum = 1;
	private int quesTotalNum = 0;

    private List<Question> questionsList = new ArrayList<Question>();

    private String startTime;
    private CountDownTimer timeCount;

    @Override
	protected void onCreate(Bundle savedInstanceState) {
        setAnimType(RIGHT_ENTER_LEFT_EXT);
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.test_real_exam_detail);


        setReturnBtn();

		viewPager = (MyViewPager) findViewById(R.id.viewPager);

		examPaperID = Integer.toString(((DS_Exam)getIntent().getSerializableExtra("exam")).getExamPaperID());
		setActivityTitle(((DS_Exam)getIntent().getSerializableExtra("exam")).getExamPaperName());

        setRightBtnBackgroundAndListener(R.drawable.exam_detail_rightbtn_selector, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CheckDone()){
                    submitAnswer();
                }
            }
        });

		doProgress = (TextView) findViewById(R.id.doProgress);
		wrongNum = (TextView) findViewById(R.id.wrongNum);
        haveTime = (TextView) findViewById(R.id.haveTime);
		
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int arg0) {
				quesHavedoNum = arg0 + 1;
				setQuesNum();
				
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if((questionViewList.size()>0)
					&&(questionViewList.get(arg0)!=null)){
				}
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});

        getExamDetail();

        startCountTime();

        startTime = TimeHelp.geTime("HH:mm:ss");

	}


    private void getExamDetail() {
        DS_Exam exam = DBStore.read(DS_Exam.class, ConstAnts.DB_TABLE_REALL_EXAM_OFFLINE_QUES_LIST, " ExamPaperID=" + examPaperID);

        if(exam!=null){
            progressDialog.setMessage("正在读取数据...");
            progressDialog.show();

            final Handler handler = new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    if((quesList != null) && (quesList.size()>0)){
                        quesTotalNum = quesList.size();
                        showQuestion();

                        setQuesNum();

                    }else{
                        showToast("读取数据失败！");
                    }

                    progressDialog.dismiss();
                }
            };

            new Thread(){
                @Override
                public void run() {
                    quesList = DBStore.readAll(DS_Exam_detail_ques.class,
                            ConstAnts.DB_TABLE_REALL_EXAM_OFFLINE_QUES_DETAIL+examPaperID);

                    handler.sendEmptyMessage(0);
                }
            }.start();

            return;
        }



		BaseAjaxParams params = new BaseAjaxParams();
		params.put(HttpInterface.HIF_GetRealExamDetail.params.ExamPaperID, examPaperID);
		
		FinalHttp fh = new FinalHttp();
		fh.post(HttpInterface.HIF_GetRealExamDetail.address, params, new MyAjaxCallBack<Object>(this) {

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				
				Gson gson = new Gson();
				Type listType = new TypeToken<List<DS_Exam_detail_ques>>(){}.getType();
				quesList = gson.fromJson((String)t, listType);
				
				if(quesList != null){
					quesTotalNum = quesList.size();
					showQuestion();

					setQuesNum();
				}else{
					showToast("获取问卷失败！");
				}
			}
			
		});
		

	}

	//跳转到上次做题的地方
	protected void jumpToHaveDone() {
		int haveDoneNum;
		FinalDb db = FinalDb.create(this, ConstAnts.BRKJ_DB);
		List<DS_QuesRecord> savedList = db.findAllByWhere(DS_QuesRecord.class, 
				" ExamPaperID=" + examPaperID); 
		
		if((savedList!=null) && (savedList.size()>0)){
			haveDoneNum = savedList.get(0).getHaveDownNum();

			viewPager.setCurrentItem(haveDoneNum);
		}
	}

	protected void showQuestion() {
		for(int i=0; i<quesList.size(); i++){
			QuestionItem questionItem;
            if(i == 0){
                questionItem = new QuestionItem(quesList.get(i), false, true);
            }else if(i== (quesList.size()-1)){
				questionItem = new QuestionItem(quesList.get(i), true, false);
			}else{
				questionItem = new QuestionItem(quesList.get(i), false, false);
			}
			
			questionViewList.add(questionItem);
			
			views.add(questionItem.getView());
		}
		viewPager.setViews(views);
	}
	
	private class QuestionItem{
	
		private View questionItemView;
		private DS_Exam_detail_ques quesItem;
		private boolean isCount = false;
		private boolean isDoWrong = false;
		private boolean isFirst = false;
		private boolean isLast = false;
		private Question question;

		public QuestionItem(final DS_Exam_detail_ques quesItem, boolean isLast, boolean isFirst){
			this.quesItem = quesItem;
			this.isLast = isLast;
			this.isFirst = isFirst;

		}
		
		public View getView(){
			
			question = new Question(RealExamDetailActivity.this, quesItem);
            questionsList.add(question);

			questionItemView = LayoutInflater.from(RealExamDetailActivity.this).inflate(R.layout.test_real_exam_detail_ques_item, null);
			LinearLayout questionView = (LinearLayout) questionItemView.findViewById(R.id.questionView);
			Button preBtn = (Button) questionItemView.findViewById(R.id.preBtn);
			Button nextBtn = (Button) questionItemView.findViewById(R.id.nextBtn);


            if(isFirst){
                preBtn.setVisibility(View.GONE);
            }else{
                preBtn.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.goPre();
                    }
                });
            }

            if(isLast){
                nextBtn.setText("考试完成");
                nextBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        if(CheckDone()){
                            submitAnswer();
                        }
                    }
                });
            }else{
                nextBtn.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        viewPager.goNext();
                    }
                });
            }


			questionView.addView(question.getView());
			
			
			return questionItemView;
		}

	}



	private void setQuesNum(){
		doProgress.setText("做题进度："+ quesHavedoNum + "/" + quesTotalNum );
	}
	
	public class IfBeginDoDialog {
		protected Button ok;
		protected Button cancle;
		
		protected Dialog dialog;

		public IfBeginDoDialog() {
			dialog = new Dialog(RealExamDetailActivity.this, R.style.MyCustomDialog);
			dialog.setContentView(R.layout.dialog_if_begin_do);

			ok = (Button) dialog.findViewById(R.id.ok);
			cancle = (Button) dialog.findViewById(R.id.cancle);
		
			cancle.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			
			ok.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					jumpToHaveDone();
					dialog.dismiss();
				}
			});
		}
		
		
		public void show(){
			dialog.show();
		}
	}

    public  String accuracy(double num, double total, int scale){
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        //可以设置精确几位小数
        df.setMaximumFractionDigits(scale);
        //模式 例如四舍五入
        df.setRoundingMode(RoundingMode.HALF_UP);
        double accuracy_num = num / total * 100;
        return df.format(accuracy_num)+"%";
    }

    public  double accuracyRate(double num, double total, int scale){
        DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
        //可以设置精确几位小数
        df.setMaximumFractionDigits(scale);
        //模式 例如四舍五入
        df.setRoundingMode(RoundingMode.HALF_UP);
        double accuracy_num = num / total * 100;
        return accuracy_num;
    }

    public class ResultDialog {
		protected Button back;
		
		protected Dialog dialog;

		public ResultDialog(int rightNum) {
			dialog = new Dialog(RealExamDetailActivity.this, R.style.MyCustomDialog);
			dialog.setContentView(R.layout.test_exam_result_dialog);

			back = (Button) dialog.findViewById(R.id.back);
            ((TextView) dialog.findViewById(R.id.startTime)).setText("开始时间："+ startTime);
            String useTime = (EXAM_TIME - untilFinishedTime)/60000 +1 + "分钟";
            ((TextView) dialog.findViewById(R.id.useTime)).setText("答题时长：" + useTime);
            ((TextView) dialog.findViewById(R.id.quesNum)).setText("试题数量：" + quesTotalNum+ "道");
            ((TextView) dialog.findViewById(R.id.rightNum)).setText("答对题数：" + rightNum+ "道");
            ((TextView) dialog.findViewById(R.id.rightRate)).setText("正确率：" + accuracy((double)rightNum, (double)quesTotalNum, 1));

            String resultText;
            if(accuracyRate((double)rightNum, (double)quesTotalNum, 1)<60){
                resultText = "不合格";
            }else if(accuracyRate((double)rightNum, (double)quesTotalNum, 1)<80){
                resultText = "合格";
            }else{
                resultText = "优秀";
            }

            ((TextView) dialog.findViewById(R.id.resultText)).setText(resultText);


			back.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					finish();
				}
			});
		}
		
		
		public void show(){
			dialog.show();
		}
	}

    //检查哪些题没做
    private boolean CheckDone(){
        List<HashMap<String, Integer>> haveNotDoList = new ArrayList<HashMap<String, Integer>>();

        for(int i =0; i< questionsList.size(); i++){
            if(questionsList.get(i).getAnswer().equals("")){
                HashMap<String, Integer> hashMap=new HashMap<String, Integer>();
                hashMap.put("num", i+1);
                haveNotDoList.add(hashMap);
            }
        }

        if(haveNotDoList.size() > 0){

            CheckDoneDialog dialog = new CheckDoneDialog(haveNotDoList);

            dialog.show();

            return false;
        }

        return true;
    }

    public class CheckDoneDialog {
		protected Button cancle;
		protected Button ok;
        private GridView gridView;

		protected Dialog dialog;

		public CheckDoneDialog(final List<HashMap<String, Integer>> haveNotDoList) {
			dialog = new Dialog(RealExamDetailActivity.this, R.style.MyCustomDialog);
			dialog.setContentView(R.layout.test_exam_check_done_dialog);

            cancle = (Button) dialog.findViewById(R.id.cancle);
            ok = (Button) dialog.findViewById(R.id.ok);
            gridView = (GridView) dialog.findViewById(R.id.haveNotDoGridView);

            gridView.setAdapter(new SimpleAdapter(RealExamDetailActivity.this,haveNotDoList,
                    R.layout.test_real_exam_have_not_do_item, new String[]{"num"},
                    new int[]{R.id.num}));

            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    viewPager.setCurrentItem(haveNotDoList.get(position).get("num")-1);
                    dialog.dismiss();
                }
            });

            cancle.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});

            ok.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

                    submitAnswer();
				}
			});
		}


		public void show(){
			dialog.show();
		}
	}
	
	@Override
	public void finish() {

		Intent intent = new Intent();
		intent.setAction("com.brkj.examHaveDoneChanged");
		sendBroadcast(intent);
		
		super.finish();

	}



    private void startCountTime() {

        timeCount = new CountDownTimer(EXAM_TIME, 1000){
            @Override
            public void onTick(long millisUntilFinished) {

                SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");//初始化Formatter的转换格式。

                String hms = formatter.format(millisUntilFinished);

                haveTime.setText("剩余时间：" + hms);

                untilFinishedTime = millisUntilFinished;

                if(millisUntilFinished == 5*60*1000){
                    showToast("还有5分钟，抓紧点！");
                }
            }

            @Override
            public void onFinish() {
                CommonDialog dialog = new CommonDialog(RealExamDetailActivity.this, "时间已到，请交卷！", new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        submitAnswer();
                    }
                });

                dialog.show();
            }
        };

        timeCount.start();
    }


    private  void submitAnswer(){
        int rightNum =0;
        for(DS_Exam_detail_ques exam: quesList){
            for(Question question:questionsList){
                if((exam.getUTID() == question.getUTID())&&
                (exam.getAnswer().toLowerCase().equals(question.getAnswer().toLowerCase()))){
                    rightNum++;
                }
            }
        }


        ResultDialog dialog = new ResultDialog(rightNum);
        dialog.show();


        JSONArray jsonArray = new JSONArray();

        for(int i=0; i<questionsList.size(); i++ ){

            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("num", i+1);
                jsonObject.put("UTID", questionsList.get(i).getUTID());
                jsonObject.put("type", questionsList.get(i).getType());
                jsonObject.put("answer", questionsList.get(i).getAnswer());

                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }



        BaseAjaxParams params = new BaseAjaxParams();
        params.put(HttpInterface.HIF_SubmitRealExamResult.params.ExamPaperID, examPaperID);
        params.put(HttpInterface.HIF_SubmitRealExamResult.params.AnswerJson, jsonArray.toString());


        FinalHttp fh = new FinalHttp();
        fh.post(HttpInterface.HIF_SubmitRealExamResult.address, params, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);

//                if(NomalResult.doResult(o, RealExamDetailActivity.this)){
                    showToast("答题结果已提交到服务器");
//                }
            }
        });

        timeCount.cancel();
    }

}
